package controllers

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"fmt"
	"strconv"
	"strings"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/sessions"
	rc "github.com/rongcloud/server-sdk-go/v3/sdk"
)

type GroupMessage struct {
	Ctx iris.Context
}

type GroupMessageReq struct {
	channel    string `json:"channel"`     //mini:小程序, wechat:公众号, android:安卓, ios:苹果
	objectName string `json:"object_name"` //消息类型
	content    string `json:"content"`     //消息内容
}

func (c *GroupMessage) PostMessage() interface{} {
	channel := c.Ctx.PostValue("channel")
	objectName := c.Ctx.PostValue("objectName")
	content := c.Ctx.PostValue("content")

	if channel == "" || objectName == "" || content == "" {
		return utils.CommonRes(1000, "获取参数有误", "")
	}

	//获取userId
	var userId int64
	if strings.EqualFold(channel, "wechat") {
		token := c.Ctx.GetHeader("token")
		claims, err := utils.ParseToken(token)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("解析token出错：%s", err.Error()), "")
		}
		userId = utils.Atoi64(claims.Id)
	} else {
		session := sessions.Get(c.Ctx)
		userId, _ = session.GetInt64(fmt.Sprintf("%sUserId", channel))
	}

	//连接数据库
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	userInfo := new(models.User)

	msg := rc.TXTMsg{
		Content: content,
	}

	//获取collegeCode
	ok, err := db.Table("user").ID(userId).Get(userInfo)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("根据userId查询出错:%s", err.Error()), "")
	}

	if ok {
		//创建融云对象   appid appkey 需要换
		rongCloud := rc.NewRongCloud("x18ywvqfx4c1c", "Y3Vo93Qk1cC")
		if rongCloud == nil {
			return utils.CommonRes(1000, fmt.Sprintf("创建融云对象失败"), "")
		}

		userID := strconv.FormatInt(userId, 10)
		//发送群消息
		err := rongCloud.GroupSend(userID, []string{userInfo.CollegeCode}, []string{}, objectName, &msg, "", "", 1, 0)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("发送消息失败:%s", err.Error()), "")
		}

	}

	return utils.CommonRes(20000, "发送群消息成功", "")
}
